//
//  RegisterViewController.swift
//  WangPu
//
//  Created by xiaozhi on 15/9/25.
//  Copyright (c) 2015年 zhixiao. All rights reserved.
//

import UIKit
enum ActionType{
    case Register,ForgetPassword
}
class RegisterViewController: BaseViewController {
    var type:ActionType = ActionType.Register
    var commitButton:UIButton!
    var confirmDataBtn:UIButton!
    var userName:MyTextField!
    var authorCode:MyTextField!
    var passward:MyTextField!
    var passwardAgain:MyTextField!
    var line1,line2,line3,line4:UIImageView!
    var currentTextField:UITextField?
    var  localAuthCode:String = ""
     @IBAction func commitBtnClick(sender:AnyObject)->Void{
        if !userName.text!.isValidPhoneNumber(){
            self.showTips("请输入正确手机号码")
            return
        }
        if let name = self.authorCode.text{
            let nameinfo = name.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) as NSString
            if nameinfo.length == 0{
                self.showTips("验证码不能为空")
                return
            }
        }
        else{
            self.showTips("验证码不能为空")
            return
        }
        if localAuthCode != self.authorCode.text{
            self.showTips("验证码不正确")
            return
        }
        if let pwd = self.passward.text{
            let nameinfo = pwd.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) as NSString
            if nameinfo.length == 0{
                self.showTips("密码不能为空")
                return
            }
        }
        else{
            self.showTips("密码不能为空")
            return
        }
        if let pwd = self.passwardAgain.text{
            let nameinfo = pwd.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) as NSString
            if nameinfo.length == 0{
                self.showTips("密码不能为空")
                return
            }
        }
        else{
            self.showTips("密码不能为空")
            return
        }
        if self.passward.text != self.passwardAgain.text{
            self.showTips("密码不一致")
            return
        }
        if type == ActionType.Register{

            let request = NetWorkHelper()
            let parameters = NSMutableDictionary()
            parameters.setObject(userName.text!, forKey: "phone")
            parameters.setObject("1", forKey: "register")
            parameters.setObject(passward.text!, forKey: "pwd")
            parameters.setObject(passwardAgain.text!, forKey: "pwd2")
            parameters.setObject(authorCode.text!, forKey: "authCode")
            request.requestStart("/account/register", parameters: parameters,compeleteHandle:{ (data, response, error)  in
                dispatch_async(dispatch_get_main_queue()){
                    self.hiddenProcessView()
                }
                if error == nil{
                    var dic:NSDictionary?
                    do {
                        dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                    } catch let error as NSError {
                        print(error)
                        dispatch_async(dispatch_get_main_queue()){
                            self.showTips("服务器数据异常")
                        }
                        return
                    }
                    if (dic?["result"])! as! String == "0"{
                        dispatch_async(dispatch_get_main_queue()){
                            self.showTips("注册成功"){
                                //                                self.loginSuccess?(userInfo: dic?["data"] as? NSDictionary)
                                self.navigationController?.popViewControllerAnimated(true)
                            }
                        }
                    }
                    else{
                        dispatch_async(dispatch_get_main_queue(), {[weak self] in
                            self?.showTips(dic?["msg"] as? String)
                            })
                        
                    }
                }
            })
            self.showProcess("正在处理...")
        }
        else{
            let request = NetWorkHelper()
            let parameters = NSMutableDictionary()
            parameters.setObject(userName.text!, forKey: "phone")
            parameters.setObject(passward.text!, forKey: "pwd")
            parameters.setObject(passwardAgain.text!, forKey: "pwd2")
            parameters.setObject(authorCode.text!, forKey: "authCode")
            request.requestStart("/account/forgetPWD", parameters: parameters,compeleteHandle:{ (data, response, error)  in
                dispatch_async(dispatch_get_main_queue()){
                    self.hiddenProcessView()
                }
                if error == nil{
                    var dic:NSDictionary?
                    do {
                        dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                    } catch let error as NSError {
                        print(error)
                        dispatch_async(dispatch_get_main_queue()){
                            self.showTips("服务器数据异常")
                        }
                        return
                    }
                    if (dic?["result"])! as! String == "0"{
                        dispatch_async(dispatch_get_main_queue()){
                            self.showTips("密码修改成功"){
//                                self.loginSuccess?(userInfo: dic?["data"] as? NSDictionary)
                                self.navigationController?.popViewControllerAnimated(true)
                            }
                        }
                    }
                    else{
                        dispatch_async(dispatch_get_main_queue(), {[weak self] in
                            self?.showTips(dic?["msg"] as? String)
                            })

                    }

                }
            })
            self.showProcess("正在处理...")
        }
    }
    @IBAction func getConfirmData(sender:AnyObject)->Void{
        if !userName.text!.isValidPhoneNumber(){
            self.showTips("请输入正确手机号码")
            return
        }
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        parameters.setObject(userName.text!, forKey: "phone")
        if type == ActionType.Register{
            parameters.setObject("0", forKey: "register")
        }
        else{
            parameters.setObject("1", forKey: "register")
        }
        request.requestStart("/account/authCode", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                } catch let error as NSError {
                    print(error)
                    dispatch_async(dispatch_get_main_queue()){
                        self.showTips("服务器数据异常")
                    }
                    return
                }
                if (dic?["result"])! as! String == "0"{
                    dispatch_async(dispatch_get_main_queue()){
                        self.confirmDataBtn.addCount()
                        if let number =  dic?["data"] as? String{
                            self.localAuthCode = number
                        }
                    }
                }
            }
        })

    }
    override func viewDidLoad() {
        super.viewDidLoad()
        switch type{
        case ActionType.Register:
            self.title = "注册"
        case ActionType.ForgetPassword:
            self.title = "忘记密码"
        default:break
        }
        let backItem = UIBarButtonItem(image: UIImage(named: "back_icon"), style:UIBarButtonItemStyle.Plain, target:self, action:"back:")
        backItem.tintColor = UIColor.whiteColor()
        self.navigationItem.leftBarButtonItem = backItem
        view.backgroundColor = UIColor.whiteColor()
        self.createLoginInfo()
        // Do any additional setup after loading the view.
    }
    func createLoginInfo()->Void{
        var rect:CGRect
        //用户名
        userName = MyTextField(frame: CGRectMake(10,64, view.bounds.size.width, 50))
        userName.borderStyle = UITextBorderStyle.None
        userName.placeholder = "用户名"
        userName.font = UIFont.systemFontOfSize(14)
        userName.delegate = self
        var leftView1 = UIImageView(frame: CGRectMake(10, 0, 16, 16))
        leftView1.image = UIImage(named: "user1")
        userName.leftView = leftView1
        userName.leftViewMode = UITextFieldViewMode.Always
        view.addSubview(userName)
        
        line1 = UIImageView(frame: CGRectMake(10, CGRectGetMaxY(userName.frame), view.bounds.size.width-20, 1))
        line1.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.1)
        view.addSubview(line1)
        
        //验证码
        rect = userName.frame
        rect.origin.y = CGRectGetMaxY(line1.frame)
        rect.size.width -= 100
        authorCode = MyTextField(frame:rect)
        authorCode.borderStyle = UITextBorderStyle.None
        authorCode.placeholder = "短信验证码"
        authorCode.font = UIFont.systemFontOfSize(14)
        authorCode.delegate = self
        leftView1 = UIImageView(frame: CGRectMake(10, 0, 16, 16))
        leftView1.image = UIImage(named: "message")
        authorCode.leftView = leftView1
        authorCode.leftViewMode = UITextFieldViewMode.Always
        view.addSubview(authorCode)
        
        confirmDataBtn = UIButton(type: UIButtonType.System)
        confirmDataBtn.frame=CGRectMake(view.bounds.size.width-100, CGRectGetMidY(authorCode.frame)-15, 85, 30)
        confirmDataBtn.backgroundColor = commonRedColor
        confirmDataBtn.titleLabel?.font = UIFont.systemFontOfSize(14)
        confirmDataBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        confirmDataBtn.setTitle("获取验证码", forState: UIControlState.Normal)
        confirmDataBtn.layer.cornerRadius = 4.0
        confirmDataBtn.addTarget(self, action: "getConfirmData:", forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(confirmDataBtn)
        
        line2 = UIImageView(frame: CGRectMake(10, CGRectGetMaxY(authorCode.frame), view.bounds.size.width-20, 1))
        line2.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.1)
        view.addSubview(line2)
        //密码
        rect = userName.frame
        rect.origin.y = CGRectGetMaxY(line2.frame)
        passward = MyTextField(frame: rect)
        passward.borderStyle = UITextBorderStyle.None
        passward.placeholder = "密码"
        passward.font = UIFont.systemFontOfSize(14)
        passward.secureTextEntry = true
        passward.delegate = self
        leftView1 = UIImageView(frame: CGRectMake(10, 0, 16, 16))
        leftView1.image = UIImage(named: "lock")
        passward.leftView = leftView1
        
        passward.leftViewMode = UITextFieldViewMode.Always
        view.addSubview(passward)
        
        line3 = UIImageView(frame: CGRectMake(10, CGRectGetMaxY(passward.frame), view.bounds.size.width-20, 1))
        line3.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.1)
        view.addSubview(line3)
        //再次输入密码
//        if type == ActionType.Register{
//            rect = userName.frame
//            rect.origin.y = CGRectGetMaxY(line3.frame)
//            passwardAgain = MyTextField(frame: rect)
//            passwardAgain.borderStyle = UITextBorderStyle.None
//            passwardAgain.placeholder = "再次输入密码"
//            passwardAgain.font = UIFont.systemFontOfSize(14)
//            passwardAgain.delegate = self
//            passwardAgain.secureTextEntry = true
//            leftView1 = UIImageView(frame: CGRectMake(10, 0, 16, 16))
//            leftView1.image = UIImage(named: "lock")
//            passwardAgain.leftView = leftView1
//            passwardAgain.leftViewMode = UITextFieldViewMode.Always
//            view.addSubview(passwardAgain)
//            
//            line4 = UIImageView(frame: CGRectMake(10, CGRectGetMaxY(passwardAgain.frame), view.bounds.size.width-20, 1))
//            line4.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.1)
//            view.addSubview(line4)
//        }
        rect = userName.frame
        rect.origin.y = CGRectGetMaxY(line3.frame)
        passwardAgain = MyTextField(frame: rect)
        passwardAgain.borderStyle = UITextBorderStyle.None
        passwardAgain.placeholder = "再次输入密码"
        passwardAgain.font = UIFont.systemFontOfSize(14)
        passwardAgain.delegate = self
        passwardAgain.secureTextEntry = true
        leftView1 = UIImageView(frame: CGRectMake(10, 0, 16, 16))
        leftView1.image = UIImage(named: "lock")
        passwardAgain.leftView = leftView1
        passwardAgain.leftViewMode = UITextFieldViewMode.Always
        view.addSubview(passwardAgain)
        
        line4 = UIImageView(frame: CGRectMake(10, CGRectGetMaxY(passwardAgain.frame), view.bounds.size.width-20, 1))
        line4.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.1)
        view.addSubview(line4)
        
        //提交
        commitButton = UIButton(type: UIButtonType.System)
        commitButton.frame=CGRectMake(15, CGRectGetMaxY(line3.frame)+passward.bounds.size.height+20, view.bounds.size.width-30, 35)
        commitButton.layer.cornerRadius = 4.0
        commitButton.backgroundColor = UIColor(red: 194/255.0, green: 0.0, blue: 22/255.0, alpha: 1.0)
        commitButton.addTarget(self, action: "commitBtnClick:", forControlEvents: UIControlEvents.TouchUpInside)
        commitButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        commitButton.setTitle("提交", forState: UIControlState.Normal)
        commitButton.titleLabel?.font = UIFont.systemFontOfSize(14)
        view.addSubview(commitButton)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewWillAppear(animated: Bool){
        super.viewWillAppear(animated)
        navigationController?.navigationBarHidden = false
    }
    func back(barButtonItem:UIBarButtonItem){
        self.navigationController?.popViewControllerAnimated(true)
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
extension RegisterViewController:UITextFieldDelegate{
    func textFieldDidBeginEditing(textField: UITextField){
        self.currentTextField = textField
    }
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        self.currentTextField?.resignFirstResponder()
        return true
    }
}
